﻿using System.Collections.Generic;
using System.Web.Mvc;
using System.Linq;
using Gfw.BLL.Basic.User;
using Gfw.Web.Models.User;
using Gfw.Web.Models.Account;
using Gfw.Web.Areas.Admin.Models;
using System;
using Gfw.Web.Common;
using Gfw.BLL.Basic.Account;
using Gfw.Infrastructure.ExceptionImpl;

namespace Gfw.Web.Areas.Admin.Controllers
{
    [LAuthorize(RequireRole="Kf")]
    public class UserController : Controller
    {
        #region Const Field

        private const string PAGEINDEX_CASH = "PageIndex_Cash";
        private const string PAGEINDEX_X = "PageIndex_X";
        private const string PAGEINDEX_D = "PageIndex_D";
        private const string PAGEINDEX_G = "PageIndex_G";

        private const string USERCONTROLLER_ERROR_CASH = "Error_Cash";
        private const string USERCONTROLLER_ERROR_X = "Error_X";
        private const string USERCONTROLLER_ERROR_D = "Error_D";
        private const string USERCONTROLLER_ERROR_G = "Error_G";

        private const string USERCONTROLLER_BANKSERIALNO = "Cash_BankSerialNo";
        private const string USERCONTROLLER_TRADEABSTRACT = "Cash_TradeAbstract";
        private const string USERCONTROLLER_LOGINNAME = "LoginName";

        private const int SUCCESS_RECHARGE = 1;

        #endregion

        #region Session

        //BMK Session
        /// <summary>
        /// 查询
        /// </summary>
        private CommonQueryModel QueryModel
        {
            get { return Session["UserController_CommonQueryModel"].ConvertTo<CommonQueryModel>(null); }
            set { Session["UserController_CommonQueryModel"] = value; }
        }

        /// <summary>
        /// 当前选择的页数（充值）
        /// </summary>
        private int RechargePageIndex
        {
            get { return Session["UserController_PageIndex_Recharge"].ConvertTo<int>(1); }
            set { Session["UserController_PageIndex_Recharge"] = value; }
        }

        /// <summary>
        /// 当前选择的页数（提现）
        /// </summary>
        private int CashPageIndex
        {
            get { return Session["UserController_PageIndex_Cash"].ConvertTo<int>(1); }
            set { Session["UserController_PageIndex_Cash"] = value; }
        }

        #endregion

        #region Search User

        //BMK Search
        /// <summary>
        /// 根据会员注册名查找会员信息
        /// </summary>
        /// <param name="loginName">会员注册名</param>
        /// <returns></returns>
        public ActionResult Index(string loginName)
        {
            return View();
        }

        /// <summary>
        /// 返回指定的会员页面
        /// </summary>
        /// <param name="loginName">用户登录名</param>
        /// <returns></returns>
        public ActionResult List(string loginName)
        {
            if (string.IsNullOrEmpty(loginName))
                return null;

            var model = UserLogic.GetUserBindingInfo(loginName);
            if (model == null)
                return PartialView(null);

            List<UserBindingInfoModel> list = new List<UserBindingInfoModel>();
            list.Add(model);
            return PartialView(list);
        }

        #endregion

        #region User Information

        // BMK Information
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns></returns>
        public ActionResult Details(string userID)
        {
            try
            {
                UserFullDetailModel model = UserLogic.GetUserFullDetailInfoByUserID(userID);
                if (model == null)
                    return HttpNotFound();

                return View(model);
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return HttpNotFound(ex.Message);
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public ActionResult Edit(string loginName)
        {
            UserBindingInfoModel model = UserLogic.GetUserBindingInfo(loginName);
            if (model == null)
                return HttpNotFound();

            var bankList = new UserBankListModel();
            ViewBag.BankList = new SelectList(bankList.ToList<string>());
            return View(model);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(UserBindingInfoModel model)
        {
            try
            {
                UserLogic.EditUserBindingInfo(model); // 修改：只改身份证号
                UserLogic.EditUserFinanceInfo(model);

                return RedirectToAction("Index", new { loginName = model.LoginName });
            }
            catch (System.Exception ex)
            {
                return View(model);
            }
        }

        /// <summary>
        /// 封号/解锁
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public ActionResult Lock(string loginName)
        {
            UserBindingInfoModel model = UserLogic.GetUserBindingInfo(loginName);
            if (model == null)
                return HttpNotFound();

            return View(model);
        }

        /// <summary>
        /// 封号/解锁
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isLock">true:封号；false:解锁</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Lock(UserBindingInfoModel model, bool isLock)
        {
            try
            {
                model.IsLock = isLock;
                UserLogic.EditUserBindingInfo(model);

                return RedirectToAction("Index", new { loginName = model.LoginName });
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
        }

        #endregion

        #region User Recharge

        //BMK Recharge
        /// <summary>
        /// 充值查询
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="userID">用户ID</param>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult RechargeIndex(string loginName, string userID, CommonQueryModel model)
        {
            TempData[USERCONTROLLER_LOGINNAME] = ViewBag.LoginName = loginName;

            model.Key = userID;
            QueryModel = model;
            RechargePageIndex = 1;

            return View(model);
        }

        /// <summary>
        /// 返回充值指定页面
        /// </summary>
        /// <param name="page">从第一页开始计算</param>
        /// <returns></returns>
        public ActionResult RechargeList(int? page)
        {
            int totalSize, countRecharge;
            decimal sumRecharge, maxRecharge, minRecharge;
            int index = page ?? RechargePageIndex;
            if (index < 1) index = 1;

            var list = UserAccountLogic.RechargeQuery(QueryModel.Key, TempData[USERCONTROLLER_LOGINNAME] as string, QueryModel.StartDate.Value, QueryModel.EndDate.Value, index - 1, ViewHelper.PageSize, out totalSize, out countRecharge, out sumRecharge, out maxRecharge, out minRecharge);

            ViewBag.TotalSize = totalSize;
            ViewBag.LoginName = TempData[USERCONTROLLER_LOGINNAME];
            ViewBag.CountRecharge = countRecharge;
            ViewBag.SumRecharge = sumRecharge;
            ViewBag.MaxRecharge = maxRecharge;
            ViewBag.MinRecharge = minRecharge;

            RechargePageIndex = ViewBag.PageIndex = index;

            TempData[USERCONTROLLER_LOGINNAME] = ViewBag.LoginName;
            return PartialView(list);
        }

        /// <summary>
        /// 会员充值
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="userID"></param>
        /// <param name="done">改页面是否转账完成，如果是，则需要显示提示框</param>
        /// <returns></returns>
        public ActionResult CreateRecharge(string loginName, string userID, bool? done)
        {
            ViewBag.Done = done.HasValue ? done.Value : false;
            UserRechargeModel model = new UserRechargeModel()
            {
                UserID = userID,
                LoginName = loginName,
                HandlerID = L.Manage.Authentication.Context.CurrentUser.Id,
                Status = SUCCESS_RECHARGE,
            };

            return View(model);
        }

        [HttpPost]
        public ActionResult CreateRecharge(UserRechargeModel model)
        {
            ViewBag.Done = false;
            try
            {
                if (model == null)
                    return HttpNotFound();

                UserAccountLogic.Recharge(model);
                return RedirectToAction("CreateRecharge", new { done = true });
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
        }

        #endregion

        #region User Cash

        //BMK Cash
        /// <summary>
        /// 提现查询
        /// </summary>
        /// <param name="loginName">登录名，可查指定用户</param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="cashType">wait:0;cancel:-1;pass:1;不填:全部</param>
        /// <returns></returns>
        public ActionResult CashIndex(string loginName, string start, string end, string cashType)
        {
            TempData[USERCONTROLLER_BANKSERIALNO] = TempData[USERCONTROLLER_TRADEABSTRACT] = null;

            try
            {
                var cashTypeList = new UserCashCheckTypeListModel();
                ViewBag.CashTypeList = new SelectList(cashTypeList.ToList<string>(), "审核中"); // 含默认值
                ViewBag.CashType = cashType;


                DateTime startDate, endDate;
                if (!string.IsNullOrEmpty(start) &&
                    !DateTime.TryParse(start, out startDate))
                {
                    ModelState.AddModelError("", "开始日期不正确！");
                    TempData[USERCONTROLLER_ERROR_CASH] = USERCONTROLLER_ERROR_CASH;
                }
                else if (!string.IsNullOrEmpty(end) &&
                    !DateTime.TryParse(end, out endDate))
                {
                    ModelState.AddModelError("", "结束日期不正确！");
                    TempData[USERCONTROLLER_ERROR_CASH] = USERCONTROLLER_ERROR_CASH;
                }
                else if (!string.IsNullOrEmpty(loginName))
                {
                    string userID = UserLogic.GetUserIDByLoginName(loginName); // 获取该用户的用户ID

                    if (string.IsNullOrEmpty(userID))
                    {
                        ModelState.AddModelError("", "用户名不存在！");
                        TempData[USERCONTROLLER_ERROR_CASH] = USERCONTROLLER_ERROR_CASH;
                    }

                    ViewBag.UserID = userID; // 保存userID
                }
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                TempData[USERCONTROLLER_ERROR_CASH] = USERCONTROLLER_ERROR_CASH;
            }

            return View();
        }

        /// <summary>
        /// 提现查询结果，返回提现指定页面
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="loginName">只用于显示，不参加逻辑！</param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="cashType"></param>
        /// <param name="page">从第一页开始计算</param>
        /// <returns></returns>
        public ActionResult CashList(string userID, string loginName, DateTime? start, DateTime? end, string cashType, int? page)
        {
            try
            {
                if (TempData[USERCONTROLLER_ERROR_CASH] != null)
                {
                    ViewBag.TotalSize = 0;
                    ViewBag.PageIndex = 0;

                    return PartialView(null); // 返回一个空值!显示：“没有相关信息”
                }

                if (TempData[PAGEINDEX_CASH] == null)
                    TempData[PAGEINDEX_CASH] = 1;

                int totalSize, index = page ?? (int)TempData[PAGEINDEX_CASH];

                if (index < 1)
                    index = 1;

                var list = UserAccountLogic.CashQuery(userID, loginName, cashType, start, end, index, ViewHelper.PageSize, out totalSize);
                ViewBag.TotalSize = totalSize;
                TempData[PAGEINDEX_CASH] = ViewBag.PageIndex = index;

                ViewBag.StartDate = start;
                ViewBag.EndDate = end;

                return PartialView(list);
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                ViewBag.TotalSize = 0;
                ViewBag.PageIndex = 0;

                return PartialView(null);
            }
        }

        /// <summary>
        /// 提现用户详细信息
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="applyDate">申请时间</param>
        /// <returns></returns>
        public ActionResult CashDetails(string userID, DateTime applyDate)
        {
            try
            {
                if (string.IsNullOrEmpty(userID))
                    return HttpNotFound();

                CashDetailModel model = UserLogic.GetUserCashDetailInfoByUserID(userID, applyDate);
                if (model == null)
                    return HttpNotFound();

                return View(model);
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return HttpNotFound(ex.Message);
            }
        }

        /// <summary>
        /// 提现用户审核（审核通过 | 审核不通过）
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="applyDate">申请时间</param>
        /// <param name="loginName">只用于显示，不参加逻辑！</param>
        /// <param name="d">该页面确认审核，并显示提示框</param>
        /// <param name="check">用于提示框显示</param>
        /// <param name="end">用于返回查询保存查询条件</param>
        /// <param name="start">用于返回查询保存查询条件</param>
        /// <returns></returns>
        public ActionResult CashCheck(string loginName, string userID, DateTime applyDate,
            bool? d, string check, DateTime? start, DateTime? end)
        {
            try
            {
                ViewBag.LoginName = loginName;
                ViewBag.Done = d.HasValue ? d.Value : false;
                ViewBag.Check = check;
                ViewBag.StartDate = start;
                ViewBag.EndDate = end;

                var model = UserAccountLogic.GetUserCashApplyInfo(userID, applyDate);

                TempData[USERCONTROLLER_BANKSERIALNO] = model.BankSerialNo = TempData[USERCONTROLLER_BANKSERIALNO] as string;
                TempData[USERCONTROLLER_TRADEABSTRACT] = model.TradeAbstract = TempData[USERCONTROLLER_TRADEABSTRACT] as string;

                return View(model);
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return HttpNotFound(ex.Message);
            }
        }

        /// <summary>
        /// 提现用户审核（审核通过 | 审核不通过）
        /// </summary>
        /// <param name="check">标志（通过 | 不通过）</param>
        /// <param name="applyDate">申请时间，单独出来原因：model 里修改不了！</param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CashCheck(CashQueryCmpModel model, string check, DateTime applyDate,
            DateTime? start, DateTime? end)
        {
            ViewBag.Done = false;
            ViewBag.Check = check;
            ViewBag.StartDate = start;
            ViewBag.EndDate = end;


            TempData[USERCONTROLLER_BANKSERIALNO] = model.BankSerialNo;
            TempData[USERCONTROLLER_TRADEABSTRACT] = model.TradeAbstract;

            model.RequireDate = applyDate;

            return RedirectToAction("CashCheck", new
            {
                loginName = model.LoginName,
                userID = model.UserID,
                applyDate = model.RequireDate,
                d = true,
                check = check,
                start = start,
                end = end,
            });
        }

        /// <summary>
        /// 确认审核
        /// </summary>
        /// <param name="userID">申请会员ID</param>
        /// <param name="applyDate">申请时间</param>
        /// <param name="count">申请金额</param>
        /// <param name="isCheckPass">true: 审核通过；false: 审核不通过</param>
        /// <returns></returns>
        public ActionResult CashCheckConfirm(string userID, DateTime applyDate, long count, bool isCheckPass,
            DateTime? start, DateTime? end)
        {
            try
            {
                UserAccountLogic.CashCheck(userID, applyDate, count, L.Manage.Authentication.Context.CurrentUser.Id,
                    TempData[USERCONTROLLER_BANKSERIALNO] as string,
                    TempData[USERCONTROLLER_TRADEABSTRACT] as string, isCheckPass);

                return RedirectToAction("CashCheckResult", new { start = start, end = end });
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return HttpNotFound(ex.Message);
            }
        }

        /// <summary>
        /// 审核结果界面
        /// </summary>
        /// <returns></returns>
        public ActionResult CashCheckResult(DateTime? start, DateTime? end)
        {
            TempData[USERCONTROLLER_BANKSERIALNO] = TempData[USERCONTROLLER_TRADEABSTRACT] = null;

            ViewBag.StartDate = start;
            ViewBag.EndDate = end;

            return View();
        }

        #endregion

        #region User Reset

        // BMK Reset
        /// <summary>
        /// 重置登录密码
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public ActionResult ResetLoginPassword(string loginName)
        {
            UserLogic.ResetLoginPassword(loginName);
            return RedirectToAction("List", new { loginName = loginName });
        }

        /// <summary>
        /// 重置二级密码
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public ActionResult ResetSecondPassword(string loginName)
        {
            UserLogic.ResetSecondPassword(loginName);
            return RedirectToAction("List", new { loginName = loginName });
        }

        /// <summary>
        /// 重置密保问题
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public ActionResult ResetSecurityQuestion(string loginName)
        {
            UserLogic.ResetSecurityQuestion(loginName);
            return RedirectToAction("List", new { loginName = loginName });
        }

        #endregion

        #region User Commission

        /// <summary>
        /// 收取修改资料手续费，每次100元
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public ActionResult GetCommission(string userID, string loginName)
        {
            UserAccountLogic.GetCommission(userID, loginName);
            return RedirectToAction("List", new { loginName = loginName });
        }

        #endregion

        #region User Account Query -- X:Cash | D:EMoney | G:Stock | 动态奖金

        /// <summary>
        /// 现金X币查询
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="loginName">用于显示，不作逻辑操作</param>
        /// <param name="cashType"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult CashQuery(string loginName, string userID, string start, string end, string tradeType)
        {
            try
            {
                if (string.IsNullOrEmpty(userID))
                    return HttpNotFound();

                ViewBag.LoginName = loginName;

                UserCashTradeTypeListModel tradeTypeList = new UserCashTradeTypeListModel();
                ViewBag.TradeTypeList = new SelectList(tradeTypeList.GetUserCashTradeTypeList(), "Value", "Key");

                DateTime startDate, endDate;
                if (!string.IsNullOrEmpty(start) &&
                    !DateTime.TryParse(start, out startDate))
                {
                    ModelState.AddModelError("", "开始日期不正确！");
                    TempData[USERCONTROLLER_ERROR_X] = USERCONTROLLER_ERROR_X;
                }
                else if (!string.IsNullOrEmpty(end) &&
                    !DateTime.TryParse(end, out endDate))
                {
                    ModelState.AddModelError("", "结束日期不正确！");
                    TempData[USERCONTROLLER_ERROR_X] = USERCONTROLLER_ERROR_X;
                }
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                TempData[USERCONTROLLER_ERROR_X] = USERCONTROLLER_ERROR_X;
            }

            return View();
        }

        /// <summary>
        /// 现金X币查询结果，返回查询指定页面
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="tradeType"></param>
        /// <param name="page">从第一页开始计算</param>
        /// <returns></returns>
        public ActionResult CashQueryList(string userID, DateTime? start, DateTime? end, string tradeType, int? page)
        {
            try
            {
                ViewData.Add("userID", userID);
                ViewData.Add("start", start);
                ViewData.Add("end", end);
                ViewData.Add("tradeType", tradeType);

                if (TempData[USERCONTROLLER_ERROR_X] != null)
                {
                    ViewBag.TotalSize = 0;
                    ViewBag.PageIndex = 0;

                    return PartialView(null); // 返回一个空值!显示：“没有相关信息”
                }

                if (TempData[PAGEINDEX_X] == null)
                    TempData[PAGEINDEX_X] = 1;

                int totalSize, index = page ?? (int)TempData[PAGEINDEX_X];

                if (index < 1)
                    index = 1;

                var list = UserAccountLogic.Bargain4CashQuery(userID, tradeType, start, end, index, ViewHelper.PageSize, out totalSize);
                ViewBag.TotalSize = totalSize;
                TempData[PAGEINDEX_X] = ViewBag.PageIndex = index;

                return PartialView(list);
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                ViewBag.TotalSize = 0;
                ViewBag.PageIndex = 0;

                return PartialView(null);
            }
        }



        /// <summary>
        /// 电子D币查询
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="loginName">用于显示，不作逻辑操作</param>
        /// <param name="tradeType"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult EMoneyQuery(string loginName, string userID, string start, string end, string tradeType)
        {
            try
            {
                if (string.IsNullOrEmpty(userID))
                    return HttpNotFound();

                ViewBag.LoginName = loginName;

                UserEMoneyTradeTypeListModel tradeTypeList = new UserEMoneyTradeTypeListModel();
                ViewBag.TradeTypeList = new SelectList(tradeTypeList.GetUserEMoneyTradeTypeList(), "Value", "Key");

                DateTime startDate, endDate;
                if (!string.IsNullOrEmpty(start) &&
                    !DateTime.TryParse(start, out startDate))
                {
                    ModelState.AddModelError("", "开始日期不正确！");
                    TempData[USERCONTROLLER_ERROR_D] = USERCONTROLLER_ERROR_D;
                }
                else if (!string.IsNullOrEmpty(end) &&
                    !DateTime.TryParse(end, out endDate))
                {
                    ModelState.AddModelError("", "结束日期不正确！");
                    TempData[USERCONTROLLER_ERROR_D] = USERCONTROLLER_ERROR_D;
                }
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                TempData[USERCONTROLLER_ERROR_D] = USERCONTROLLER_ERROR_D;
            }

            return View();
        }

        /// <summary>
        /// 电子D币查询，返回查询指定页面
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="tradeType"></param>
        /// <param name="page">从第一页开始计算</param>
        /// <returns></returns>
        public ActionResult EMoneyQueryList(string userID, DateTime? start, DateTime? end, string tradeType, int? page)
        {
            try
            {
                ViewData.Add("userID", userID);
                ViewData.Add("start", start);
                ViewData.Add("end", end);
                ViewData.Add("tradeType", tradeType);

                if (TempData[USERCONTROLLER_ERROR_D] != null)
                {
                    ViewBag.TotalSize = 0;
                    ViewBag.PageIndex = 0;

                    return PartialView(null); // 返回一个空值!显示：“没有相关信息”
                }

                if (TempData[PAGEINDEX_D] == null)
                    TempData[PAGEINDEX_D] = 1;

                int totalSize, index = page ?? (int)TempData[PAGEINDEX_D];

                if (index < 1)
                    index = 1;

                var list = UserAccountLogic.Bargain4EMoneyQuery(userID, tradeType, start, end, index, ViewHelper.PageSize, out totalSize);
                ViewBag.TotalSize = totalSize;
                TempData[PAGEINDEX_D] = ViewBag.PageIndex = index;

                return PartialView(list);
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                ViewBag.TotalSize = 0;
                ViewBag.PageIndex = 0;

                return PartialView(null);
            }
        }



        /// <summary>
        /// 股票G币查询
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public ActionResult StockQuery(string userID)
        {
            if (string.IsNullOrEmpty(userID))
                return HttpNotFound();

            return View();
        }

        //////////////////////////////////////////////////////////////////////////

        #endregion
    }
}